package com.pactera.jep.service.sys.web.controller;

import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.commons.StringUtils;
import com.pactera.jep.core.code.YesNo;
import com.pactera.jep.core.context.Context;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.OrderType;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.code.NotifyConfigType;
import com.pactera.jep.sys.code.NotifyStatus;
import com.pactera.jep.sys.code.StaffNotifyStatus;
import com.pactera.jep.sys.dto.StaffNotifyDto;
import com.pactera.jep.sys.model.Notify;
import com.pactera.jep.sys.model.StaffNotify;
import com.pactera.jep.sys.service.NotifyService;
import com.pactera.jep.sys.service.StaffNotifyService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.code.WebHeaderCode;
import com.pactera.jep.web.util.RequestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Yangyao
 * @time 2018年06月27日 20:43
 * @company 文思海辉技术有限公司
 */
@Api(value = "消息中心")
@RestController
@RequestMapping("/staffNotify")
public class StaffNotifyRestController extends BaseRestController<StaffNotify> {
    Logger logger = LoggerFactory.getLogger(StaffNotifyRestController.class);

    @Autowired
    private StaffNotifyService staffNotifyService;

    @Autowired
    private NotifyService notifyService;

    /**
     * 为列表页面做数据准备
     */
    @Override
    protected void prepareQuery(@ApiIgnore @RequestHeader(WebHeaderCode.X_USER_TOKEN) String token, Page<StaffNotify> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {

        staffNotifyService.query(page, filters, orders);
    }

    /**
     * 查询某个用户的所有消息
     * @param page
     * @param
     * @param request
     * @return
     */
    @ApiOperation(value = "查询某个用户的所有消息")
    @GetMapping(value = "/queryNotifyByStaffCode")
    public Map<String, Object> queryNotifyByStaffCode(Page<StaffNotifyDto> page, HttpServletRequest request)
    {
        Map<String, Object> result = new HashMap<String, Object>();

        List<Order> orders = RequestUtils.buildOrders(request);
        orders.add(new Order("createTime", OrderType.DESC));

        List<Filter> filters = RequestUtils.buildFilters(request);
        String staffCode = Context.getIdentityContext().getIdentity().getId();
        filters.add(new Filter("staffCode", staffCode));

        staffNotifyService.queryNotifyByStaffCode(page, filters, orders);

        result.put("pageNumber", page.getPageNumber());
        result.put("staffName", Context.getIdentityContext().getIdentity().getName());
        result.put("pages", page.getPages());
        result.put("pageSize", page.getPageSize());
        result.put(RESULT_TOTAL, page.getTotal());
        result.put(RESULT_ROWS, page.getResult());
        return result;
    }



    /**
     * 查询某个用户的私信
     */
    @ApiOperation(value = "查询某个用户的私信")
    @GetMapping(value = "/queryMessageByStaffCode")
    public Map<String, Object> queryMessageByStaffCode(Page<StaffNotifyDto> page, HttpServletRequest request)
    {
        Map<String, Object> result = new HashMap<String, Object>();

        List<Order> orders = RequestUtils.buildOrders(request);
        orders.add(new Order("createTime", OrderType.DESC));

        List<Filter> filters = RequestUtils.buildFilters(request);
        String staffCode = Context.getIdentityContext().getIdentity().getId();
        filters.add(new Filter("staffCode", staffCode));
        List<String> types = new ArrayList<>();
        types.add(NotifyConfigType.MESSAGE.getValue());
        filters.add(new Filter("type",types ));
        filters.add(new Filter("status", StaffNotifyStatus.INBOX.getValue()));

        staffNotifyService.queryNotifyByStaffCode(page, filters, orders);

        result.put("pageNumber", page.getPageNumber());
        result.put("staffName", Context.getIdentityContext().getIdentity().getName());
        result.put("pages", page.getPages());
        result.put("pageSize", page.getPageSize());
        result.put(RESULT_TOTAL, page.getTotal());
        result.put(RESULT_ROWS, page.getResult());
        return result;
    }


    /**
     * 标记为已读
     * @param ids
     * @return
     */
    @ApiOperation(value = "标记为已读")
    @PostMapping(value = "/markAsRead")
    public Map<String, Object> markAsRead(@RequestBody String ids){

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            staffNotifyService.markAsRead(ids);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_MARK);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_MARK);
        }

        return tips;
    }

    /**
     * 全部标记为已读
     * @param
     * @return
     */
    @ApiOperation(value = "全部标记为已读")
    @PostMapping(value = "/markAllAsRead")
    public Map<String, Object> markAllAsRead(){

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            staffNotifyService.markAllAsRead();
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_MARK);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_MARK);
        }

        return tips;
    }

    /**
     * 标记为未读
     * @param ids
     * @return
     */
    @ApiOperation(value = "标记为未读")
    @PostMapping(value = "/markAsUnread")
    public Map<String, Object> markAsUnread(@RequestBody String ids){

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            staffNotifyService.markAsUnread(ids);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_MARK);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_MARK);
        }

        return tips;
    }

    /**
     * 逻辑删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "逻辑删除")
    @PostMapping(value = "/deleteFlag")
    public Map<String, Object> deleteFlag(@RequestBody String ids){

        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
             staffNotifyService.deleteFlag(ids);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
        }

        return tips;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "逻辑删除")
    @DeleteMapping(value = "/deleteCompletely")
    public Map<String, Object> remove(@RequestBody String ids){

        Map<String, Object> tips = new HashMap<String, Object>();

        try
        {
            staffNotifyService.deleteCompletely(ids);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
        }

        return tips;
    }

    /**
     * 恢复
     * @param ids
     * @return
     */
    @ApiOperation(value = "恢复")
    @PostMapping(value = "/recovery")
    public Map<String, Object> recovery(@RequestBody String ids){

        Map<String, Object> tips = new HashMap<String, Object>();

        try
        {
            staffNotifyService.recovery(ids);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_RECOVERY);
        }
        catch (ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_RECOVERY);
        }

        return tips;
    }

    @ApiOperation(value = "获取未读和垃圾信息数量")
    @GetMapping(value = "/synch")
    public Map<String, Object> synch(){
        Map<String, Object> result = new HashMap<String, Object>();
        String staffCode = Context.getIdentityContext().getIdentity().getId();
        long inboxUnread = staffNotifyService.count(
                new Filter.Builder().eq("staffCode", staffCode).
                        eq("read", YesNo.NO.getValue()).eq("status", StaffNotifyStatus.INBOX.getValue()).build() );
        result.put("inboxUnread", inboxUnread);

        long draftUnsend = notifyService.count(
                new Filter.Builder().eq("sender", staffCode)
                        .eq("status", NotifyStatus.DRAFT.getValue()).eq("type", NotifyConfigType.MESSAGE.getValue()).build());
        result.put("draftUnsend", draftUnsend);

        return result;
    }
}
